import React from 'react';
import { Bookmark, Category } from '../../types';

interface BookmarkCardProps {
  bookmark: Bookmark;
  categories: Category[];
}

const BookmarkCard: React.FC<BookmarkCardProps> = ({ bookmark, categories }) => {
  const category = categories.find(cat => cat.id === bookmark.categoryId);
  
  // 提取网站域名
  const getDomain = (url: string) => {
    try {
      const urlObj = new URL(url);
      return urlObj.hostname.replace('www.', '');
    } catch (e) {
      return url;
    }
  };

  // 获取favicon
  const getFavicon = (url: string) => {
    try {
      const domain = getDomain(url);
      return `https://www.google.com/s2/favicons?domain=${domain}&sz=64`;
    } catch (e) {
      return '';
    }
  };

  // 根据分类ID获取颜色
  const getCategoryColor = (categoryId: string) => {
    const colors: Record<string, string> = {
      '1': 'bg-blue-500', // 科技
      '2': 'bg-green-500', // 教育
      '3': 'bg-yellow-500', // 娱乐
      '4': 'bg-purple-500', // 社交
      '5': 'bg-red-500', // 新闻
      '6': 'bg-pink-500', // 购物
      '7': 'bg-indigo-500', // 工具
      '8': 'bg-gray-500', // 其他
    };
    
    return colors[categoryId] || 'bg-gray-500';
  };

  const openBookmark = () => {
    window.open(bookmark.url, '_blank');
  };

  return (
    <div 
      className="bookmark-card bg-white rounded-lg shadow-sm p-4 flex flex-col h-full border border-gray-100 hover:shadow-md transition-shadow duration-200"
      onClick={openBookmark}
    >
      <div className="flex items-start mb-2">
        <img 
          src={getFavicon(bookmark.url)} 
          alt="网站图标" 
          className="w-6 h-6 mr-2 rounded-sm flex-shrink-0"
          onError={(e) => {
            // 加载失败时显示默认图标
            (e.target as HTMLImageElement).src = '';
          }}
        />
        <div className="flex-grow min-w-0">
          <h3 className="text-sm font-medium text-gray-800 mb-1 truncate" title={bookmark.title}>
            {bookmark.title}
          </h3>
          <p className="text-xs text-gray-500 truncate" title={bookmark.url}>
            {getDomain(bookmark.url)}
          </p>
        </div>
      </div>
      
      <div className="mt-auto pt-2 flex justify-between items-center">
        {category && (
          <span className={`text-xs px-2 py-1 rounded-full text-white ${getCategoryColor(category.id)}`}>
            {category.name}
          </span>
        )}
        <span className="text-xs text-gray-400">
          {new Date(bookmark.dateAdded || 0).toLocaleDateString()}
        </span>
      </div>
    </div>
  );
};

export default BookmarkCard; 